package com.stylefeng.guns.modular.huamao.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mysql.fabric.xmlrpc.base.Data;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.CacheUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;

import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.util.StringUtils;

/**
 * 购物车控制器
 *
 * @author fengshuonan
 * @Date 2018-05-10 14:49:28
 */
@CrossOrigin()
@Controller
@RequestMapping("/sktCarts")
public class SktCartsController extends BaseController {

    private String PREFIX = "/huamao/sktCarts/";

    @Autowired
    private ISktCartsService sktCartsService;
    
    @Autowired
    private ISktOrderGoodsService sktOrderGoodsService;
    
    @Autowired
    private ISktOrdersService sktOrdersService;
    
    @Autowired
    private IAccountService accountService;

    @Autowired
    private IGoodsSpecsService goodsSpecsService;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISktShopsService sktShopsService;


    /**
     * 跳转到购物车首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "sktCarts.html";
    }

    /**
     * 跳转到添加购物车
     */
    @RequestMapping("/sktCarts_add")
    public String sktCartsAdd() {
        return PREFIX + "sktCarts_add.html";
    }

    /**
     * 跳转到修改购物车
     */
    @RequestMapping("/sktCarts_update/{sktCartsId}")
    public String sktCartsUpdate(@PathVariable Integer sktCartsId, Model model) {
        SktCarts sktCarts = sktCartsService.selectById(sktCartsId);
        model.addAttribute("item",sktCarts);
        LogObjectHolder.me().set(sktCarts);
        return PREFIX + "sktCarts_edit.html";
    }

    /**
     * 获取购物车列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return sktCartsService.selectList(null);
    }
    /**
     * 购物车结算
     * @param userId
     * @return
     */
    @RequestMapping(value = "/cartsSettlement")
    @ResponseBody
    public Object cartsSettlement(Integer userId, BigDecimal goodsMoney, String param){

        List<Map<String, Object>> listMap = JSON.parseObject(param, new TypeReference<List<Map<String,Object>>>(){});

    	Result result =  new Result();
    	JSONObject obj = sktCartsService.cartsSettlement(userId, goodsMoney,listMap);

    	if(obj.getBooleanValue("success")){

    	    Map<String,Object> map = new HashMap<String, Object>();
    	    map.put("sktOrdersListId",obj.get("sktOrdersListId"));
    	    map.put("cartScore",obj.get("cartScore"));
    		result.setType(1);
    		result.setEntity(map);
    		result.setMessage("Success");
   		result.setMessageCode(200);
    	}else{
    		result.setType(0);
    		result.setMessage(obj.get("obj").toString());
    		result.setMessageCode(500);
    	}
    	return result;
    	
    	/**
    	 * 获取订单号跟流水账号
    	 *//*
    	String orderNo = StringUtils.getOrderIdByTime("2");
    	String orderunique  = StringUtils.getOrderIdByTime("2");
    	*//**
    	 * 获取会员账户
    	 *//*
    	Account account = new Account();
    	Account accountr = new Account();
    	account.setUserId(userId);
    	EntityWrapper<Account> ewacc=new EntityWrapper<Account>();
    	ewacc.setEntity(account);
    	accountr = accountService.selectOne(ewacc);
  
    	*//**
    	 * 添加订单记录并获取订单id
    	 *//*
    	@SuppressWarnings("unused")
    	Date date = new Date(); 
    	SktOrders sktOrders = new SktOrders();
    	sktOrders.setOrderNo(orderNo);
    	sktOrders.setUserId(userId);
    	sktOrders.setOrderunique(orderunique);
    	sktOrders.setCash(accountr.getCash());
    	sktOrders.setOrderStatus(0);
    	sktOrders.setGoodsMoney(goodsMoney);
    	sktOrders.setCreateTime(date);
    	
    	sktOrdersService.insert(sktOrders);
    	//sktOrdersService.produceOrders(sktOrders);
    	*//**
    	 * 从购物车获取订单商品，添加到订单商品表
    	 *//*
    	SktCarts sktCarts = new SktCarts();
    	sktCarts.setUserId(userId);
    	List<SktOrderGoods> list = sktCartsService.selectCartsSettlementByuserId(userId);
    	for(SktOrderGoods sktOrderGoods:list){
    		sktOrderGoods.setOrderId(sktOrders.getOrderId());
    	}
    	sktOrderGoodsService.insertBatch(list);
    	*//**
    	 * 删除对应的购物车信息
    	 *//*
    	EntityWrapper<SktCarts> ew=new EntityWrapper<SktCarts>();
    	ew.setEntity(sktCarts);
    	sktCartsService.delete(ew);
    	return "success";*/
    }
    
    
    /**
     * 新增购物车
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SktCarts sktCarts,String specIds) {
        Result result =  new Result();
        boolean flag=true;
        if (flag==false){
            result.setType(0);
            result.setMessage("购买功能已关闭");
            return  result;
        }

        Integer userId=sktCarts.getUserId();
        Integer goodsId=sktCarts.getGoodsId();
        Goods sktgoods= goodsService.selectById(goodsId);
        if (sktgoods.getIsSale()==0 || sktgoods.getGoodsStatus()==-1){
            return   Result.EEROR("该商品已下架");
        }
        if ( sktgoods.getGoodsStatus()!=1){
            return   Result.EEROR("该商品为违规商品或者正在审核中");
        }
        Integer shopId=sktgoods.getShopId();
        SktShops shops = sktShopsService.selectById(shopId);
        if (shops.getShopStatus()==0){
           result.setType(0);
           result.setMessage("该店铺已关闭");
           return  result;

        }
        if (shops.getIsSelf()==0){
            boolean b=true;
            if(b==false){
                result.setType(0);
                result.setMessage("非自营店商品无法购买");
                return  result;
            }
        }
        Integer shopUserId = shops.getUserId();
        if(userId.equals(shopUserId)){
            result.setType(0);
            result.setMessage("不可以购买自己店铺的商品");
            return  result;
        }
        /**
         * 如果没有规格设置为0
         *
         * 设置查询条件，去掉查询的数量，不同的数量也可以是同种商品
         * 加入购物车时默认选中。
         */

        /**
         * sktCarts的GoodsSpecId由于前段没有获取到，需要程序通过specIds等字段查询获得
         *
         */
        GoodsSpecs goodsSpecs = new GoodsSpecs();
        goodsSpecs.setGoodsId(sktCarts.getGoodsId());
        if(specIds == "" || specIds == null){
            goodsSpecs.setSpecIds("0");
        }else{
            goodsSpecs.setSpecIds(specIds);
        }

        EntityWrapper<GoodsSpecs> entityWrapper1  = new EntityWrapper<GoodsSpecs>(goodsSpecs);
        GoodsSpecs rgoodsSpecs = new GoodsSpecs();
        rgoodsSpecs  = goodsSpecsService.selectOne(entityWrapper1);
        /**
         *如果规格不存在提示物品已售完-_-！
         */
        if (rgoodsSpecs == null){
            if(!StringUtils.isBlank(specIds)){
                return  Result.EEROR("此物品已售完！");
            }

        }
        /**
         * 从数据库中取出库存，放到缓存中。
         * 先判断缓存中有没有对应的库存
         */
        // 库存ID
    //    Integer goodsId  = sktCarts.getGoodsId();
        String redisKey = "redis_key:stock:" + goodsId;
        if(!cacheUtil.isKeyInCache(redisKey)){
            /**
             * 缓存的数据格式
             *redisKey:{
             *     "goodsStock":goodsStock,
             *     "isSpec":true/false,
             *     "spec": {
             *         specId:specStock,
             *     }
             *}
             */
            JSONObject map = new JSONObject();

            Goods goods = new Goods();
            goods = goodsService.selectById(goodsId);
            map.put("goodsStock",goods.getGoodsStock());
            if(specIds == "" || specIds == null){
                map.put("isSpec",false);
            }else{
                map.put("isSpec",true);
                JSONObject specsMap = new JSONObject();
                GoodsSpecs goodsSpecs1 =  new GoodsSpecs();
                goodsSpecs1.setGoodsId(goodsId);
                EntityWrapper<GoodsSpecs> entityWrapper =  new EntityWrapper<GoodsSpecs>(goodsSpecs1);
                List<GoodsSpecs> goodsSpecsList  = goodsSpecsService.selectList(entityWrapper);
                for(GoodsSpecs temp:goodsSpecsList){
                    specsMap.put(temp.getId().toString(),temp.getSpecStock());
                }
                map.put("spec",specsMap);
            }

            cacheUtil.set(redisKey,map, Long.valueOf(60*30));
        };
        //cacheUtil.remove(redisKey);

        SktCarts sktCarts1 = new SktCarts();
        sktCarts1.setIsDirect(sktCarts.getIsDirect());
        if(specIds == "" || specIds == null){
            sktCarts1.setUserId(sktCarts.getUserId());
            sktCarts1.setIsCheck(1);
            sktCarts1.setGoodsId(sktCarts.getGoodsId());
            sktCarts1.setGoodsSpecId("0");
            sktCarts.setGoodsSpecId("0");
        }else {
            sktCarts1.setUserId(sktCarts.getUserId());
            sktCarts1.setIsCheck(1);
            sktCarts1.setGoodsId(sktCarts.getGoodsId());
            sktCarts1.setGoodsSpecId(rgoodsSpecs.getId().toString());
            sktCarts.setGoodsSpecId(rgoodsSpecs.getId().toString());
        }



    	try {
    	    EntityWrapper<SktCarts> ew = new EntityWrapper<SktCarts>(sktCarts1);
            /**
             * 查询是否有同型号的商品
             */
            SktCarts sc = sktCartsService.selectOne(ew);
            /**
             * 先判断是不是直接购买，如果是直接购买就增加一条信息
             * 如果是加入购物车就判断规格型号
             * 如果没有同型号的商品，就增加一条商品信息
             * 如果有同型号的商品，就在改变商品的数量
             */

            if(sktCarts.getIsDirect().equals(1)) {
                sktCartsService.insert(sktCarts);
                result.setEntity(sktCarts.getCartId());
            }else{
                if(sc == null){
                    sktCartsService.insert(sktCarts);
                    result.setEntity(sktCarts.getCartId());
                }else{
                    int temp = sc.getCartNum() + sktCarts.getCartNum();
                    sc.setCartNum(temp);
                    EntityWrapper<SktCarts> entityWrapper = new EntityWrapper<SktCarts>(sc);
                    sktCartsService.updateById(sc);
                    result.setEntity(sc.getCartId());
                }
            }


    		result.setType(1);

    		result.setMessage("Success");
    		result.setMessageCode(200);
		} catch (Exception e) {
			result.setType(0);
    		result.setMessage("添加失败");
    		result.setMessageCode(500);
		}

    	return result;
    	
    }

    /**
     * 删除购物车
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Transactional
    public Object delete(@RequestParam String sktCartsId) {
        String[] strs=sktCartsId.split(",");
    	Result result =  new Result();
    	try {
            for(int i=0;i<strs.length;i++){
                sktCartsService.deleteById(Integer.parseInt(strs[i]));
            }
    		//sktCartsService.deleteById(sktCartsId);
    		result.setType(1);
    		result.setMessage("Success");
    		result.setMessageCode(200);
		} catch (Exception e) {
			result.setType(0);
    		result.setMessage("删除失败");
    		result.setMessageCode(500);
		}
    	
    	return result;
        
    }
    /**
     * 根据用户id查询订单商品表
     * @param userId
     * @return
     */
    @RequestMapping(value = "/selectCartsByuserId")
    @ResponseBody
    public Object selectCartsByuserId(Integer userId,Integer isDirect){

        Map<String,Object> map  = new HashMap<String, Object>();
        map.put("userId",userId);
        map.put("isDirect",isDirect);

    	Result result =  new Result();
    	try {
    		Object object = sktCartsService.selectCartsByuserId(map);
    		result.setType(1);
    		result.setMessage("Success");
    		result.setMessageCode(200);
    		result.setEntity(object);
		} catch (Exception e) {
			result.setType(0);
    		result.setMessage("查询失败");
    		result.setMessageCode(500);
		}
    	
    	return result;
    }
    /**
     * 修改购物车
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SktCarts sktCarts) {
        sktCartsService.updateById(sktCarts);
        return SUCCESS_TIP;
    }

    /**
     * 购物车详情
     */
    @RequestMapping(value = "/detail/{sktCartsId}")
    @ResponseBody
    public Object detail(@PathVariable("sktCartsId") Integer sktCartsId) {
        return sktCartsService.selectById(sktCartsId);
    }
}
